<template>
  <ul
    class="collapse-container"
    v-if="data && data.length > 0"
  >
    <li
      class="collapse-item"
      :class="item.isExpand ? 'active' : ''"
      v-for="item in data"
      :key="item.id"
    >
      <div class="item-container">
        <div class="item-tools">
          <span class="item-tools-el icon icon-icon_delete text-link" @click="handleRemoveChild(item)"></span>
          <span class="item-tools-el icon icon-bianji1 text-link" @click="handleEditChild(item)"></span>
          <span class="item-tools-el icon icon-icon_add text-link" @click="handleAddChild(item)"></span>
        </div>
        <div
          class="item-text item-collapse collapse"
          :class="item.isChecked ? 'item-checked' : ''"
          @click="handleCheckNode(item)"
        >
          <a class="item-link">
            <i class="item-icon" @click="expand(item)"
              v-if="item.children && item.children.length > 0"
            ></i><span @click="handleActive(item)">{{item.name}}</span>
          </a>
        </div>
      </div>
      <list-collapse
        :data="item.children"
        :isRoot="false"
        @click-item="handleActive"
        @add-item="handleAddChild"
        @edit-item="handleEditChild"
        @remove-item="handleRemoveChild"
        @check-item="handleCheckNode"
      />
    </li>
  </ul>
</template>
<script>
/**
 * @description 树组件
*/

export default {
  name: 'list-collapse',
  components: {

  },

  props: {
    // 节点数组
    data: {
      type: Array,
      default () {
        return []
      }
    },
    // 是否是根
    isRoot: {
      type: Boolean,
      default () {
        return true
      }
    }
  },

  methods: {
    /**
     * @function 打开
     * @param {node} node 节点对象
    */
    expand (node) {
      this.$set(node, 'isExpand', !node.isExpand)
    },

    /**
     * @function 打开全部
    */
    expandAll (list) {
      list = list || this.data
      list = Array.isArray(list) ? list : []
      list.forEach(item => {
        this.expand(item)
        if (Array.isArray(item.children)) {
          this.expandAll(item.children)
        }
      })
    },

    /**
     * @function 点击节点
     * @param {node} node 节点对象
    */
    handleActive (node) {
      this.$emit('click-item', node)
    },

    /**
     * @function 添加节点
     * @param {node} node 节点对象
    */
    handleAddChild (node) {
      this.$emit('add-item', node)
    },

    /**
     * @function 编辑节点
     * @param {node} node 节点对象
    */
    handleEditChild (node) {
      this.$emit('edit-item', node)
    },

    /**
     * @function 删除节点
     * @param {node} node 节点对象
    */
    handleRemoveChild (node) {
      this.$emit('remove-item', node)
    },

    /**
     * @function 选中节点
     * @param {node} node 节点对象
    */
    handleCheckNode (node) {
      this.$emit('check-item', node)
    }
  }
}
</script>

<style lang="less">

</style>